#include<iostream>
#include"log.hpp"
#include"InetAddr.hpp"
#include<string>
#include"Common.hpp"



using namespace LogModule;



int main(int argc,char *argv[])
{

    if(argc!=3)
    {
        std::cout<<"Client IP Port"<<std::endl;
        exit(ExitCode::USAGE_ERR);
    }
    uint16_t port=std::stoi(argv[2]);
    std::string ip=argv[1];
    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    //客户端无需进行显示的绑定
    InetAddr addr(ip,port);
    int n=connect(sockfd,addr.GetAddr(),addr.SockLen());
    if(n<0)
    {
        std::cout<<"connect error"<<std::endl;
        exit(ExitCode::CONNECT_ERR);
    }



    char buffer[4096];
    while(1)
    {
        std::cout<<"please input:";
        std::string input;
        std::getline(std::cin,input);

        if(input=="QUIT")
        {
            break;
        }
        int n=write(sockfd,input.c_str(),input.size());
        if(n<0)
        {
            std::cout<<"write error"<<std::endl;
        }

        n=read(sockfd,buffer,sizeof(buffer));
        if(n<0)
        {
            std::cout<<"read error"<<std::endl;
            exit(ExitCode::READ_ERR);
        }
        else if(n>0)
        {
            buffer[n]=0;
            std::cout<<"Server say:"<<buffer<<std::endl;
        }
        else{
            std::cout<<"Server quit"<<std::endl;
            exit(ExitCode::READ_ERR);
        }
        
        
    }


    close(sockfd);





    return 0;
}